package ar.edu.unlu.sistemas.movirdroid.business.peer;

import java.io.IOException;
import java.net.InetSocketAddress;

import ar.edu.unlu.sistemas.movirdroid.business.net.tcp.TCPListener;
import ar.edu.unlu.sistemas.movirdroid.business.net.udp.UDPListener;
import ar.edu.unlu.sistemas.movirdroid.business.util.Logger;
import ar.edu.unlu.sistemas.movirdroid.business.util.Params;
import ar.edu.unlu.sistemas.ws.business.PeerWS;

public class Peer {
	
	public Integer id;
	public InetSocketAddress address;
	public String name;
	private TCPListener listener;
	private UDPListener udpListener;
	
	public Peer() {
		this.setId(Params.PEER_ID);
		this.setName(Params.PEER_ALIAS);
	}
	
	public void initConnection(String ipAddr) {
		try {	
			this.address = new InetSocketAddress(ipAddr, Params.TCP_LISTEN_PORT);
			this.listener = new TCPListener(Params.TCP_LISTEN_PORT);
			this.udpListener = new UDPListener(4600);
		} catch (IOException ioe) {
			Logger.logError(this.getClass().getName(), "No se pudo iniciar el puerto TCP", ioe);
		}
	}
	
	public TCPListener getListener() {
		return listener;
	}

	public void setListener(TCPListener listener) {
		this.listener = listener;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getId() {
		return id;
	}
	
	public void setId(Integer id) {
		if (id > 0 ) this.id = id;
	}
	
	public InetSocketAddress getAddress() {
		return address;
	}
	
	public void setAddress(InetSocketAddress address) {
		this.address = address;
		
	}
	
	public void stopListener() {
		this.listener.close();
	}
	
	public String toString() {
		return "id: "+this.getId()+"\nname: "+(this.getName()!=null?this.getName():"")+"\naddr: "+this.getAddress().toString();
	}

	public PeerWS getWSObject() {
		PeerWS peerWS = new PeerWS();
		peerWS.setId(this.getId() != null ? this.getId().toString() : null);
		peerWS.setAddress(this.getAddress().getAddress().getHostAddress());
		peerWS.setPort(this.getAddress().getPort());
		peerWS.setName(this.getName());
		return peerWS;
	}
	
}
